package com.ebring.shareEducation.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ebring.shareEducation.bean.User;
import com.ebring.shareEducation.service.UserService;
import com.ebring.shareEducation.util.HttpRequest;
import com.ebring.shareEducation.utils.RspMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat/userAuth")
public class AccessTokenController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccessTokenController.class);

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.appsecret}")
    private String appsecret;
    @Value("${wechat.redirect_uri}")
    private String redirect_uri;
    @Value("${wechat.userAuthUrl}")
    private String userAuthUrl;
    @Value("${wechat.accessTokenUrl}")
    private String accessTokenUrl;
    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;
    @Value("${wechat.mobileUrl}")
    private String mobileUrl;
    @Autowired
    private UserService userService;

    private static String response_type = "code";
    private static String scope = "snsapi_userinfo";
    private static String lang = "zh_CN";

    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        String state = request.getParameter("userId");
        //第一步：用户同意授权，获取code
        String url = userAuthUrl + "?appid=" + appid + "&redirect_uri=" + URLEncoder.encode(redirect_uri) + "&response_type=" + response_type + "&scope=" + scope +
                "&state=" + state + "#wechat_redirect";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/getAccessToken")
    public void getAccessToken(HttpServletRequest request, HttpServletResponse response) {
        //第二步：通过code换取网页授权access_token
        String code = request.getParameter("code");
        String userid = request.getParameter("state");
        String authParams = "appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code";
        LOGGER.info("in AccessTokenController,accessTokenUrl:" + accessTokenUrl + "?" + authParams);
        String authResult = HttpRequest.sendGet(accessTokenUrl, authParams);
        JSONObject authObject = (JSONObject) JSON.parse(authResult);
        String infoParams = "access_token=" + authObject.get("access_token") + "&openid=" + authObject.get("openid") + "&lang=" + lang;
        LOGGER.info("in AccessTokenController,userInfoUrl:" + accessTokenUrl + "?" + authParams);
        String infoResult = HttpRequest.sendGet(userInfoUrl, infoParams);
        JSONObject infoObject = (JSONObject) JSON.parse(infoResult);
        System.out.println(infoObject.getString("openid"));
        RspMsg<User> userRspMsg = userService.selectUserByUserId(userid);
        User user = userRspMsg.getResult();
        user.setOpenid(infoObject.getString("openid"));
        user.setUsername(infoObject.getString("nickname"));
        user.setImagePath(infoObject.getString("headimgurl"));
        user.setAccessToken(authObject.getString("access_token"));
        user.setRefreshToken(authObject.getString("refresh_token"));
        userService.updateUserByEntity(user);
        try {
            response.sendRedirect(mobileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
